package com.avic.rong.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.AdvertismentListBean;
import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.activity.product.DetailProductActivity;
import com.avic.rong.activity.product.OnlineCServiceActivity;
import com.avic.rong.adapter.CommandAdapter;
import com.avic.rong.adapter.show.GuangGaoAdapter;
import com.avic.rong.api.collect.DeleteCollectApi;
import com.avic.rong.api.collect.ZanCancelApi;
import com.avic.rong.api.focus_fans.FocusStateApi;
import com.avic.rong.bean.AdvBean;
import com.avic.rong.bean.CartListReloadEvent;
import com.avic.rong.bean.GoCartListEvent;
import com.avic.rong.bean.HomePageEvent;
import com.avic.rong.bean.MinePageEvent;
import com.avic.rong.bean.show_bean.DetailBean;
import com.avic.rong.bean.show_bean.EsInfoBean;
import com.avic.rong.bean.show_bean.PingBean;
import com.avic.rong.course.activity.CourseDetailActivity;
import com.avic.rong.fragment.showapi.DetailApi;
import com.avic.rong.fragment.showapi.EsInfoApi;
import com.avic.rong.fragment.showapi.PingApi;
import com.avic.rong.fragment.showapi.PingCommentApi;
import com.avic.rong.goodsSort.api.ContentAdvApi;
import com.avic.rong.questionOrAnswer.DialogShare;
import com.avic.rong.questionOrAnswer.ShareUtilCallBack;
import com.avic.rong.questionOrAnswer.activity.PersonalHomeActivity;
import com.avic.rong.richEditor.keyboard.KeyboardHeightObserver;
import com.avic.rong.richEditor.keyboard.KeyboardHeightProvider;
import com.avic.rong.richEditor.keyboard.KeyboardUtils;
import com.avic.rong.search.MessageEvent;
import com.avic.rong.shoppingCar.activity.ShoppingCarActivity;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.EditUtils;
import com.avic.rong.utils.NetWorkUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.StatusBarUtil;
import com.avic.rong.utils.StringUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.ScrollWebViewListion;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.coorchice.library.SuperTextView;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.orhanobut.logger.Logger;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;


public class VadioDetailActivity extends RxAppCompatActivity implements ShareUtilCallBack, BGASwipeBackHelper.Delegate, KeyboardHeightObserver {


    public static String ARG_URL = "arg_url";

    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.go_meng)
    ImageView goMeng;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.icon_follow_down)
    ImageView iconFollowDown;
    @BindView(R.id.user_name_down)
    TextView userNameDown;
    @BindView(R.id.user_time_down)
    TextView userTimeDown;
    @BindView(R.id.btn_follow_down)
    Button btnFollowDown;
    @BindView(R.id.webview)
    ScrollWebViewListion webview;
    @BindView(R.id.tv_middle)
    TextView tvMiddle;
    @BindView(R.id.two_zan_img)
    ImageView twoZanImg;
    @BindView(R.id.two_zan_size)
    TextView twoZanSize;
    @BindView(R.id.zanlau)
    LinearLayout zanlau;
    @BindView(R.id.tv_article_flag)
    SuperTextView tvArticleFlag;
    @BindView(R.id.rl_three)
    RelativeLayout rlThree;
    @BindView(R.id.guanggao)
    RecyclerView guanggao;
    @BindView(R.id.tv_command_number)
    TextView tvCommandNumber;
    @BindView(R.id.recycler_command)
    RecyclerView recyclerCommand;
    @BindView(R.id.scroll_article)
    NestedScrollView scrollArticle;
    @BindView(R.id.et_command)
    LinearLayout etCommand;
    @BindView(R.id.btn_collect)
    ImageView btnCollect;
    @BindView(R.id.collect_number)
    TextView collectNumber;
    @BindView(R.id.rl_collect)
    RelativeLayout rlCollect;
    @BindView(R.id.img_zan)
    ImageView imgZan;
    @BindView(R.id.img_zan_size)
    TextView imgZanSize;
    @BindView(R.id.zan_rale)
    RelativeLayout zanRale;
    @BindView(R.id.img_share)
    ImageView imgShare;
    @BindView(R.id.gongnnegkuai)
    LinearLayout gongnnegkuai;
    @BindView(R.id.rl_command)
    LinearLayout rlCommand;
    @BindView(R.id.et_fousecommand)
    EditText etFousecommand;
    @BindView(R.id.fabu)
    TextView fabu;
    @BindView(R.id.fabuimage)
    ImageView fabuimage;
    @BindView(R.id.ping_layout)
    LinearLayout pingLayout;
    @BindView(R.id.vadio_loading)
    LoadingLayout vadioLoading;

    private TextView tv_length, fensi_size, wenzhang_size,intro_text;
    private DialogShare dialogShare;

    private CommandAdapter commandAdapter;
    private String logintoken;
    //收藏标识
    private boolean isShow = false;
    //点赞标识
    private boolean isZan = false;
    //关注标识
    private boolean isFollow = false;
    //视频是否播放标识
    private boolean isPlay;
    private boolean isPause;
    private PopupWindow popupWindow;
    private View popView;
    private WebSettings settings;
    //传过来的contid展示文章内容
    private int contId;
    //内容详情中用户的ID用来跳转个人主页
    private int userId;
    //内容详情数据
    private List<DetailBean.OtherInfoBean> otherInfo;
    //广告适配器
    private GuangGaoAdapter guangGaoAdapter;
    private List<AdvBean> advertismentList;
    private BGASwipeBackHelper mSwipeBackHelper;
    private StandardGSYVideoPlayer detail_vadio;
    private OrientationUtils orientationUtils;
    private LoadingLayout vadio_loading;
    private ImageView type_8_daV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vadio_detail);
        detail_vadio = findViewById(R.id.detail_vadio);
        vadio_loading = findViewById(R.id.vadio_loading);
        fensi_size = findViewById(R.id.fensi_size);
        wenzhang_size = findViewById(R.id.wenzhang_size);
        type_8_daV = findViewById(R.id.type_8_daV);
        intro_text = findViewById(R.id.intro_text);

        tv_length = findViewById(R.id.tv_length);
        ButterKnife.bind(this);
        logintoken = SharedPreferencesUtil.getInstance(this).getLogintoken();
        Intent intent = getIntent();
        contId = intent.getIntExtra("contId", 0);
        settings = webview.getSettings();
        guangGaoAdapter = new GuangGaoAdapter(this);
        guanggao.setLayoutManager(new LinearLayoutManager(this));
        guanggao.setAdapter(guangGaoAdapter);
        initSwipeBackFinish();

        //设置状态栏颜色
        StatusBarUtil.setStatusBarColor(this, getResources().getColor(R.color.color_loginbg));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        // 设置加载进来的页面自适应手机屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        webview.addJavascriptObject(this, null);

        webview.loadUrl(AppUtils.BASE_URL + "/content/detailContent?contId=" + contId);
        webview.setWebViewClient(new WebViewClient() {
            @SuppressLint("MissingPermission")
            @Override
            public boolean shouldOverrideUrlLoading
                    (WebView view, String url) {
                Log.i("用户单击超连接", url);
                //判断用户单击的是那个超连接

                String[] split = url.split("/");


                String type = split[3].toString();
                if (type.equals("good")) {
                    String id = split[4].toString();
                    String substring = id.substring(0, id.length() - 5);
                    startActivity(DetailProductActivity.getIntent(VadioDetailActivity.this, substring));
                } else if (type.equals("rr")) {
                    String id = split[4].toString();
                    int substring = Integer.parseInt(id);
                    Intent intentype = new Intent(VadioDetailActivity.this, VadioDetailActivity.class);
                    intentype.putExtra("contId", substring);
                    startActivity(intentype);
                } else if (type.equals("peixun")) {
                    String id = split[5].toString();
                    String substring = id.substring(0, id.length() - 5);
                    startActivity(CourseDetailActivity.getIntent(VadioDetailActivity.this, substring, "", ""));
                }
                return true;
            }
        });


        iconFollowDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goPersonActivity();
            }
        });

        goMeng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopup(VadioDetailActivity.this);
            }
        });
        backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        vadio_loading.setStatus(LoadingLayout.LOADING);
        //内容详情z
        DetailApi detailApi = new DetailApi(this, DetailhttpOnNextListener, logintoken, contId + "");
        detailApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(detailApi);

        vadio_loading.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                HttpManager.getInstance().doHttpDeal(detailApi);
            }

            @Override
            public void onReturn(View v) {
                finish();
            }
        });

        //获取状态

        EsInfoApi esInfoApi = new EsInfoApi(this, EnsOnNextListener, contId + "");
        esInfoApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(esInfoApi);

        //广告
        ContentAdvApi contentAdvApi = new ContentAdvApi(VadioDetailActivity.this, bookAdvListener, ConstantsUtils.ADV_ArticleDetailsPage_photo);
        contentAdvApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(contentAdvApi);
        //关注down
        btnFollowDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharedPreferencesUtil.isLogin()) {
                    FocusStateApi focusStateApi = new FocusStateApi(VadioDetailActivity.this, htsstpOnNextListener);
                    String logintoken = SharedPreferencesUtil.getInstance(VadioDetailActivity.this).getLogintoken();
                    focusStateApi.setArgument(userId, logintoken);
                    focusStateApi.setCache(false);
                    HttpManager.getInstance().doHttpDeal(focusStateApi);
                } else {
                    ToastTools.showToast("请先登录");
                    startActivity(new Intent(VadioDetailActivity.this, LoginPhoneActivity.class));
                }

            }
        });
        //点赞
        imgZan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dianzan();
            }
        });
        zanlau.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dianzan();
            }
        });
        //收藏
        rlCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!logintoken.equals("")) {
                    DeleteCollectApi deleteCollectApi = new DeleteCollectApi(VadioDetailActivity.this, deleteCollectListener);
                    deleteCollectApi.setArgument(logintoken, 12, contId);
                    HttpManager.getInstance().doHttpDeal(deleteCollectApi);

                } else {
                    Toast.makeText(VadioDetailActivity.this, "登录后才能进行此功能", Toast.LENGTH_SHORT).show();

                    startActivity(new Intent(VadioDetailActivity.this, LoginPhoneActivity.class));
                }


            }
        });

        //分享
        imgShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //分享
                if (dialogShare == null) {
                    dialogShare = new DialogShare(VadioDetailActivity.this, VadioDetailActivity.this);
                }
                if (otherInfo != null) {
                    if (StringUtils.isEmpty(otherInfo.get(0).getContImg())) {
                        dialogShare.showDialog("我在融融上发现了一篇好的文章，想要分享给你", otherInfo.get(0).getTitle(), AppUtils.BASE_URL_H5 + "app/act/detail?contId=" + contId, "");
                    } else {
                        dialogShare.showDialog("我在融融上发现了一篇好的文章，想要分享给你", otherInfo.get(0).getTitle(), AppUtils.BASE_URL_H5 + "app/act/detail?contId=" + contId, otherInfo.get(0).getContImg());
                    }

                }
            }
        });
        tvArticleFlag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //分享
                if (dialogShare == null) {
                    dialogShare = new DialogShare(VadioDetailActivity.this, VadioDetailActivity.this);
                }
                if (otherInfo != null) {
                    if (StringUtils.isEmpty(otherInfo.get(0).getContImg())) {
                        dialogShare.showDialog("我在融融上发现了一篇好的文章，想要分享给你", otherInfo.get(0).getTitle(), AppUtils.BASE_URL_H5 + "app/act/detail?contId=" + contId, "");
                    } else {
                        dialogShare.showDialog("我在融融上发现了一篇好的文章，想要分享给你", otherInfo.get(0).getTitle(), AppUtils.BASE_URL_H5 + "app/act/detail?contId=" + contId, otherInfo.get(0).getContImg());
                    }

                }
            }
        });


        //列表展示

        PingApi pingApi = new PingApi(this, pINGhttpOnNextListener, contId);
        pingApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(pingApi);

//获取软键盘是否隐藏
        pingLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                pingLayout.getWindowVisibleDisplayFrame(rect);
                int height = pingLayout.getRootView().getHeight();
                int heightDifference = height - (rect.bottom);
                if (heightDifference > 200) {
                    pingLayout.setVisibility(View.VISIBLE);
                    rlCommand.setVisibility(View.GONE);
                    etFousecommand.setFocusable(true);
                    etFousecommand.setFocusableInTouchMode(true);
                    etFousecommand.requestFocus();
                    KeyboardUtils.showSoftInput(VadioDetailActivity.this);
                } else {
                    pingLayout.setVisibility(View.GONE);
                    rlCommand.setVisibility(View.VISIBLE);
                }
            }
        });


        etCommand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                pingLayout.setVisibility(View.VISIBLE);
                rlCommand.setVisibility(View.GONE);
//                EditUtils.showSoftKeyboard(VadioDetailActivity.this, etFousecommand);

                etFousecommand.setFocusable(true);
                etFousecommand.setFocusableInTouchMode(true);
                etFousecommand.requestFocus();
                KeyboardUtils.showSoftInput(VadioDetailActivity.this);
            }
        });


        etFousecommand.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().equals("")) {
//                    fabu.setTextColor(getResources().getColor(R.color.shadow_bg));
//                    fabu.setVisibility(View.GONE);
//                    fabuimage.setVisibility(View.VISIBLE);
                    fabuimage.setImageResource(R.mipmap.fabuimage);
                } else {
//                    fabu.setVisibility(View.GONE);
                    fabuimage.setImageResource(R.mipmap.fabuimage_3x);
//                    fabuimage.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        fabuimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendComment();
            }
        });
//        fabu.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//             ToastTools.showPublicToast("请输入内容");
//            }
//        });


//        keyboardHeightProvider = new KeyboardHeightProvider(this);
//        etFousecommand.post(new Runnable() {
//            @Override
//            public void run() {
//                keyboardHeightProvider.start();
//            }
//        });

    }



    KeyboardHeightProvider keyboardHeightProvider;

    private void dianzan() {
        if (!logintoken.equals("")) {
            ZanCancelApi zanCancelApi = new ZanCancelApi(VadioDetailActivity.this, httpOnNextListener);
            zanCancelApi.setArgument(contId, 1, logintoken);
            HttpManager.getInstance().doHttpDeal(zanCancelApi);

        } else {
            Toast.makeText(VadioDetailActivity.this, "登录后才能进行此功能", Toast.LENGTH_SHORT).show();

            startActivity(new Intent(VadioDetailActivity.this, LoginPhoneActivity.class));
        }
    }


    private void goPersonActivity() {
        Intent PresenIntent = new Intent(VadioDetailActivity.this, PersonalHomeActivity.class);
        PresenIntent.putExtra("homeUserID", userId + "");
        startActivity(PresenIntent);
    }

    //同步获取编码token
    @JavascriptInterface
    public String getLoginUserEncode(Object msg) {
        String login_token = "";
        if (SharedPreferencesUtil.isLogin()) {
            try {
                login_token = URLEncoder.encode(SharedPreferencesUtil.getLoginToken(), "UTF-8");
            } catch (Exception e) {
                Logger.i(e.getMessage());
            }
        }
        return login_token;
    }


    //发表评论
    private void sendComment() {

        if (!SharedPreferencesUtil.getInstance(this).getLoginToken().isEmpty()) {
            String trim = etFousecommand.getText().toString().trim();
            if (!trim.equals("")) {
                PingCommentApi addAnswerCommentApi = new PingCommentApi(VadioDetailActivity.this, simpleOnNextListener, contId, trim, SharedPreferencesUtil.getInstance(this).getLoginToken());
                addAnswerCommentApi.setCache(false);
                HttpManager.getInstance().doHttpDeal(addAnswerCommentApi);
                EditUtils.hideSoftKeyboard(VadioDetailActivity.this, etFousecommand);
                ToastTools.showPublicToast("评论成功");
                pingLayout.setVisibility(View.GONE);
                rlCommand.setVisibility(View.VISIBLE);
                etFousecommand.setText("");
            } else {
                Toast.makeText(VadioDetailActivity.this, "输入不能为空", Toast.LENGTH_SHORT).show();
            }
        } else {
            EditUtils.hideSoftKeyboard(VadioDetailActivity.this, etFousecommand);
            Toast.makeText(VadioDetailActivity.this, "登录后才能进行此功能", Toast.LENGTH_SHORT).show();
            pingLayout.setVisibility(View.GONE);
            rlCommand.setVisibility(View.VISIBLE);
            etFousecommand.setText("");
            startActivity(new Intent(VadioDetailActivity.this, LoginPhoneActivity.class));
        }
    }

    //广告图片
    HttpOnNextListener bookAdvListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                return;
            }
            AdvertismentListBean advertismentListBean = (AdvertismentListBean) subjects.getData();
            advertismentList = advertismentListBean.getAdvertismentList();
            guangGaoAdapter.setAdvertismentList(advertismentList);
        }


        @Override
        public void onError(final Throwable e) {
            Logger.e("cjx", "banner数据" + e.getMessage());
        }
    };

    //添加回答评论
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {

                return;
            }
            ToastTools.showPublicToast("评论成功");
            PingApi pingApi = new PingApi(VadioDetailActivity.this, pINGhttpOnNextListener, contId);
            pingApi.setCache(false);
            HttpManager.getInstance().doHttpDeal(pingApi);

            etFousecommand.setText("");

        }
    };
    //评论列表

    HttpOnNextListener<BaseResultEntity<PingBean>> pINGhttpOnNextListener = new HttpOnNextListener<BaseResultEntity<PingBean>>() {
        @Override
        public void onNext(BaseResultEntity<PingBean> listBaseResultEntity) {
            if (listBaseResultEntity.getCode().equals("200")) {
                PingBean pingBean = listBaseResultEntity.getData();
                if (pingBean != null) {
                    List<PingBean.CommentsBean> comments = pingBean.getComments();
                    tvCommandNumber.setText("全部评论（" + comments.size() + "）");
                    commandAdapter = new CommandAdapter(VadioDetailActivity.this);
                    commandAdapter.setData(comments);
                    DividerItemDecoration divider = new DividerItemDecoration(VadioDetailActivity.this, DividerItemDecoration.VERTICAL);
                    divider.setDrawable(ContextCompat.getDrawable(VadioDetailActivity.this, R.drawable.divider_follow));
                    recyclerCommand.addItemDecoration(divider);
                    recyclerCommand.setLayoutManager(new LinearLayoutManager(VadioDetailActivity.this));
                    recyclerCommand.setAdapter(commandAdapter);
                }


            }
        }

    };


    //收藏
    HttpOnNextListener<BaseResultEntity> deleteCollectListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                if (isShow) {
                    ToastTools.showPublicToast("取消收藏成功");
                    isShow = false;
                    String trim = collectNumber.getText().toString().trim();
                    int size = Integer.parseInt(trim);
                    size--;
                    collectNumber.setText(size + "");
                    Glide.with(VadioDetailActivity.this).load(R.mipmap.whitestar2x).into(btnCollect);
                } else {
                    ToastTools.showPublicToast("收藏成功");
                    isShow = true;
                    String trim = collectNumber.getText().toString().trim();
                    int size = Integer.parseInt(trim);
                    size++;
                    collectNumber.setText(size + "");
                    Glide.with(VadioDetailActivity.this).load(R.mipmap.yellowstar2x).into(btnCollect);
                }
            } else {

            }
        }
    };

    //点赞
    HttpOnNextListener<BaseResultEntity> httpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals("200")) {

                if (!isZan) {
                    ToastTools.showPublicToast("点赞成功");
                    isZan = true;
                    String trim = imgZanSize.getText().toString().trim();
                    int size = Integer.parseInt(trim);
                    size++;
                    imgZanSize.setText(size + "");
                    twoZanSize.setText(size + "");
                    Glide.with(VadioDetailActivity.this).load(R.mipmap.orangezan2x).into(imgZan);
                    Glide.with(VadioDetailActivity.this).load(R.mipmap.orangezan2x).into(twoZanImg);
                } else {
                    ToastTools.showPublicToast("取消点赞成功");
                    isZan = false;
                    String trim = imgZanSize.getText().toString().trim();
                    int size = Integer.parseInt(trim);
                    size--;
                    imgZanSize.setText(size + "");
                    twoZanSize.setText(size + "");
                    Glide.with(VadioDetailActivity.this).load(R.mipmap.whitezan2x).into(imgZan);
                    Glide.with(VadioDetailActivity.this).load(R.mipmap.whitezan2x).into(twoZanImg);
                }
            } else {
            }
        }
    };


    //判断状态
    HttpOnNextListener<BaseResultEntity> EnsOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            String code = baseResultEntity.getCode();
            if (code.equals("200")) {
                ArrayList<EsInfoBean> esInfoBean = (ArrayList<EsInfoBean>) baseResultEntity.getData();
                if (esInfoBean != null) {

                }
            }
        }
    };


    //scrool监听
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onResume() {
//        EditUtils.showORhideSoftKeyboard(ArticleDetailActivity.this);
//        keyboardHeightProvider.setKeyboardHeightObserver(this);
        EditUtils.hideSoftKeyboard(VadioDetailActivity.this, etFousecommand);
        detail_vadio.onVideoResume();
        super.onResume();
        isPause = false;
    }

    //内容详情
    HttpOnNextListener<BaseResultEntity> DetailhttpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            String code = baseResultEntity.getCode();
            if (code.equals("200")) {
                vadio_loading.setStatus(LoadingLayout.SUCCESS);
                DetailBean detailBean = (DetailBean) baseResultEntity.getData();
                userId = detailBean.getUser().getUserId();
                otherInfo = detailBean.getOtherInfo();
                String sourceUrl = detailBean.getContent().getSourceUrl();

                String intro = detailBean.getContent().getIntro();
                if (!StringUtils.isEmpty(detailBean.getContent().getIntro())) {
                    intro_text.setText(intro);
                }
                int isV = detailBean.getIsV();
                if (isV==1){
                    type_8_daV.setVisibility(View.VISIBLE);
                }
                if (otherInfo != null) {
                    tv_length.setText(otherInfo.get(0).getDuraction());
                    Glide.with(VadioDetailActivity.this).load(detailBean.getUser().getLogo())
                            .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                            .error(R.mipmap.deafult_image_header)
                            .into(iconFollowDown);
                    titleText.setText(otherInfo.get(0).getTitle());
                    fensi_size.setText(otherInfo.get(0).getFollowNum() + "粉丝");
                    wenzhang_size.setText(otherInfo.get(0).getContNum()+"文章");
                    userNameDown.setText(otherInfo.get(0).getAuthor());
                    userTimeDown.setText("发布于"+otherInfo.get(0).getPublicTime());


                    otherInfo.get(0).getContId();
                    boolean isThumb = otherInfo.get(0).isIsThumb();
                    imgZanSize.setText(otherInfo.get(0).getThumb() + "");
                    twoZanSize.setText(otherInfo.get(0).getThumb() + "");
                    //点赞
                    if (isThumb) {
                        isZan = true;
                        Glide.with(VadioDetailActivity.this).load(R.mipmap.orangezan2x).into(imgZan);
                        Glide.with(VadioDetailActivity.this).load(R.mipmap.orangezan2x).into(twoZanImg);
                    } else {
                        isZan = false;
                        Glide.with(VadioDetailActivity.this).load(R.mipmap.whitezan2x).into(imgZan);
                        Glide.with(VadioDetailActivity.this).load(R.mipmap.whitezan2x).into(twoZanImg);
                    }
                    //关注
                    isFollow = otherInfo.get(0).isIsFollow();
                    if (isFollow) {
                        btnFollowDown.setText("已关注");
                        btnFollowDown.setBackgroundResource(R.drawable.common_main_green_xian);
                        btnFollowDown.setTextColor(getResources().getColor(R.color.color_title));

                    } else {

                        btnFollowDown.setText("+ 关注");

                        btnFollowDown.setTextColor(getResources().getColor(R.color.white));
                        btnFollowDown.setBackgroundResource(R.drawable.common_main_jianbian_r2_green);

                    }
                    //收藏
                    boolean isFavorites = otherInfo.get(0).isIsFavorites();
                    int favoritesNum = otherInfo.get(0).getFavoritesNum();
                    collectNumber.setText(favoritesNum + "");
                    if (isFavorites) {
                        isShow = true;
                        Glide.with(VadioDetailActivity.this).load(R.mipmap.yellowstar2x).into(btnCollect);
                    } else {
                        isShow = false;
                        Glide.with(VadioDetailActivity.this).load(R.mipmap.whitestar2x).into(btnCollect);
                    }
                }

                if (StringUtils.isEmpty(sourceUrl)) {
                    return;
                }
                //增加封面
                ImageView imageView = new ImageView(VadioDetailActivity.this);
//                Bitmap bitmap = getNetVideoBitmap(sourceUrl);
//                imageView.setImageBitmap(bitmap);//对应的ImageView赋值图片
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                detail_vadio.setThumbImageView(imageView);
                Glide.with(VadioDetailActivity.this).load(otherInfo.get(0).getContImg())
                        .error(R.mipmap.doc_default)
                        .into(imageView);


                resolveNormalVideoUI();

                detail_vadio.getStartButton();

                //外部辅助的旋转，帮助全屏

                orientationUtils = new OrientationUtils(VadioDetailActivity.this, detail_vadio);

                //初始化不打开外部的旋转

                orientationUtils.setEnable(false);


                Map<String, String> header = new HashMap<>();

                header.put("ee", "33");

                header.put("allowCrossProtocolRedirects", "true");

                GSYVideoOptionBuilder gsyVideoOption = new GSYVideoOptionBuilder();

                gsyVideoOption.setThumbImageView(imageView)

                        .setIsTouchWiget(true)

                        .setRotateViewAuto(false)

                        .setLockLand(false)

                        .setAutoFullWithSize(false)

                        .setShowFullAnimation(false)

                        .setNeedLockFull(true)

                        .setUrl(sourceUrl)

                        .setMapHeadData(header)

                        .setCacheWithPlay(false)

                        .setVideoTitle(otherInfo.get(0).getTitle())

                        .setVideoAllCallBack(new GSYSampleCallBack() {

                            @Override

                            public void onPrepared(String url, Object... objects) {

                                super.onPrepared(url, objects);

                                //开始播放了才能旋转和全屏

                                orientationUtils.setEnable(true);
                                tv_length.setVisibility(View.GONE);
                                isPlay = true;
                                //设置 seek 的临近帧。

                            }


                            @Override

                            public void onEnterFullscreen(String url, Object... objects) {

                                super.onEnterFullscreen(url, objects);

                            }


                            @Override

                            public void onAutoComplete(String url, Object... objects) {

                                super.onAutoComplete(url, objects);
                            }

                            @Override
                            public void onClickStartIcon(String url, Object... objects) {
                                super.onClickStartIcon(url, objects);
                                tv_length.setVisibility(View.GONE);
                            }

                            @Override

                            public void onClickStartError(String url, Object... objects) {

                                super.onClickStartError(url, objects);

                            }


                            @Override

                            public void onQuitFullscreen(String url, Object... objects) {

                                super.onQuitFullscreen(url, objects);

                                Debuger.printfError("***** onQuitFullscreen **** " + objects[0]);//title

                                Debuger.printfError("***** onQuitFullscreen **** " + objects[1]);//当前非全屏player

                                if (orientationUtils != null) {

                                    orientationUtils.backToProtVideo();

                                }

                            }

                        })

                        .setLockClickListener(new LockClickListener() {

                            @Override

                            public void onClick(View view, boolean lock) {

                                if (orientationUtils != null) {

                                    //配合下方的onConfigurationChanged

                                    orientationUtils.setEnable(!lock);

                                }

                            }

                        })

                        .setGSYVideoProgressListener(new GSYVideoProgressListener() {

                            @Override

                            public void onProgress(int progress, int secProgress, int currentPosition, int duration) {

                                Debuger.printfLog(" progress " + progress + " secProgress " + secProgress + " currentPosition " + currentPosition + " duration " + duration);

                            }

                        })

                        .build(detail_vadio);
//
//                Button startButton = (Button) detail_vadio.getStartButton();
//                startButton.setBackgroundResource(videoplay);
                detail_vadio.getFullscreenButton().setOnClickListener(new View.OnClickListener() {

                    @Override

                    public void onClick(View v) {
//
//                        //直接横屏
//
                        orientationUtils.resolveByClick();

                        //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar

                        detail_vadio.startWindowFullscreen(VadioDetailActivity.this, true, true);

                    }

                });

//                detailVadio.getStartButton().setBackgroundResource(R.mipmap.videoplay);
                String networkState = NetWorkUtils.getNetworkState(VadioDetailActivity.this);
                if (networkState.equals("wifi")) {
                    detail_vadio.setNeedShowWifiTip(false);
                    detail_vadio.getStartButton().performClick();
                    tv_length.setVisibility(View.GONE);

                }
//                detailVadio.getStartButton().setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//
//                    }
//                });
                detail_vadio.setDismissControlTime(1000);
            } else {
                vadio_loading.setStatus(LoadingLayout.ERROR);
            }

        }

    };

    public static Bitmap getNetVideoBitmap(String videoUrl) {
        Bitmap bitmap = null;

        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据url获取缩略图
            retriever.setDataSource(videoUrl, new HashMap());
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }


    private void resolveNormalVideoUI() {

        //增加title

        detail_vadio.getTitleTextView().setVisibility(View.GONE);

        detail_vadio.getBackButton().setVisibility(View.GONE);

    }


    @Override

    protected void onPause() {

        detail_vadio.onVideoPause();

        super.onPause();

        isPause = true;

    }


    @Override

    public void onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();

        // 正在滑动返回的时候取消返回按钮事件

        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);

    }

    @Override

    protected void onDestroy() {
        EventBus.getDefault().post(new MessageEvent("view_num"));
        super.onDestroy();

        if (isPlay) {

            detail_vadio.release();

        }

        //GSYPreViewManager.instance().releaseMediaPlayer();

        if (orientationUtils != null)

            orientationUtils.releaseListener();

    }


    @Override

    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);

        //如果旋转了就全屏

        if (isPlay && !isPause) {

            detail_vadio.onConfigurationChanged(this, newConfig, orientationUtils, true, true);

        }

    }


    private GSYVideoPlayer getCurPlay() {

        if (detail_vadio.getFullWindowPlayer() != null) {

            return detail_vadio.getFullWindowPlayer();

        }

        return detail_vadio;

    }

    public static Intent queryIntent(Context context, String url) {
        Intent intent = new Intent(context, VadioDetailActivity.class);
        intent.putExtra(ARG_URL, url);
        return intent;
    }

    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, VadioDetailActivity.class);
        return intent;
    }

    //关注监听
    @OnClick(R.id.btn_follow_down)
    public void onViewClicked() {
        if (SharedPreferencesUtil.isLogin()) {
            FocusStateApi focusStateApi = new FocusStateApi(this, htsstpOnNextListener);
            String logintoken = SharedPreferencesUtil.getInstance(VadioDetailActivity.this).getLogintoken();
            focusStateApi.setArgument(userId, logintoken);
            focusStateApi.setCache(false);
            HttpManager.getInstance().doHttpDeal(focusStateApi);
        } else {
            ToastTools.showPublicToast("请先登录");
            startActivity(new Intent(VadioDetailActivity.this, LoginPhoneActivity.class));
        }

    }

    HttpOnNextListener<BaseResultEntity> htsstpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (!baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                return;
            }

            if (!isFollow) {

                ToastTools.showPublicToast("关注成功");

                btnFollowDown.setText("已关注");

                btnFollowDown.setBackgroundResource(R.drawable.common_main_green_xian);

                btnFollowDown.setTextColor(getResources().getColor(R.color.color_title));

                isFollow = true;
            } else {
                ToastTools.showPublicToast("取消关注成功");

                btnFollowDown.setTextColor(getResources().getColor(R.color.white));
                btnFollowDown.setBackgroundResource(R.drawable.common_main_jianbian_r2_green);

                btnFollowDown.setText("+ 关注");
                isFollow = false;
            }

        }
    };


    //分享回来
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (dialogShare != null) {
            dialogShare.initActivityResultSsoHandler(requestCode, resultCode, data);
        }


    }

    /*
     * 功能直达蒙层
     * */
    private void commonPop(View view) {
        popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
       /* // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);*/
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setClippingEnabled(false);
        //从上往下弹出动画效果
        popupWindow.setAnimationStyle(R.style.topPopupAnimation);
        popupWindow.showAtLocation(findViewById(R.id.detail_vadio), Gravity.TOP, 0, 0);
    }

    protected void showPopup(RxAppCompatActivity baseActivity) {
        popView = LayoutInflater.from(baseActivity).inflate(R.layout.function_of_direct, null, false);
        commonPop(popView);
        initListener(baseActivity);
    }

    ;

    private void initListener(Context context) {
        ImageView img_close_pop = popView.findViewById(R.id.img_close_pop);
        Button bt_home = popView.findViewById(R.id.bt_home);
        Button bt_mall = popView.findViewById(R.id.bt_mall);
        Button bt_news = popView.findViewById(R.id.bt_news);
        Button bt_own = popView.findViewById(R.id.bt_own);
        Button bt_goods_car = popView.findViewById(R.id.bt_goods_car);
        Button bt_kefu = popView.findViewById(R.id.bt_kefu);

        img_close_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        bt_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().postSticky(new HomePageEvent());
                startActivity(goMain());
            }
        });
        bt_mall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().postSticky(new GoCartListEvent());
                startActivity(goMain());
            }
        });
        bt_news.setOnClickListener(new View.OnClickListener() {//消息
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (SharedPreferencesUtil.isLogin()) {
                    EventBus.getDefault().postSticky(new CartListReloadEvent());
                    startActivity(goMain());
                } else {
                    startActivity(LoginPhoneActivity.getIntent(context, "CartListReloadEvent"));
                }
            }
        });
        bt_own.setOnClickListener(new View.OnClickListener() {//我的
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (SharedPreferencesUtil.isLogin()) {
                    EventBus.getDefault().postSticky(new MinePageEvent());
                    startActivity(goMain());
                } else {
                    startActivity(LoginPhoneActivity.getIntent(context, "MinePageEvent"));
                }
            }
        });
        bt_goods_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                startActivity(ShoppingCarActivity.queryIntent(context));
            }
        });
        bt_kefu.setOnClickListener(new View.OnClickListener() {//客服
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (SharedPreferencesUtil.isLogin()) {
                    startActivity(OnlineCServiceActivity.getIntent(context, "123456"));
                } else {
                    startActivity(LoginPhoneActivity.getIntent(context, "OnlineCServiceActivity"));
                }
            }
        });


    }

    public static Intent getIntent(Context context, String contId) {
        Intent intent = new Intent(context, VadioDetailActivity.class);
        intent.putExtra("contId", Integer.parseInt(contId));
        return intent;
    }


    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。

        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(true);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(true);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {
    }

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    @Override
    public void onSwipeBackLayoutCancel() {
    }

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    @Override
    public void onSwipeBackLayoutExecuted() {
        mSwipeBackHelper.swipeBackward();
    }


    public Intent goMain() {
        Intent intent = MainActivity.queryIntent(this);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        return intent;
    }

    @Override
    public void shareSuccess() {

    }

    @Override
    public void shareFailed() {

    }

    @Override
    public void shareCancel() {

    }

    @Override
    public void onKeyboardHeightChanged(int height, int orientation) {
        if (height > 0){//显示键盘
            etFousecommand.postDelayed(new Runnable() {
                @Override
                public void run() {
                    etFousecommand.setFocusable(true);
                    etFousecommand.setFocusableInTouchMode(true);
                    etFousecommand.requestFocusFromTouch();
                }
            },200);

        }
    }
}
